package com.rivercloud.dao.Impl;

import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.rivercloud.dao.TableRowDao;
import com.rivercloud.entity.TableRow;

public class TableRowDaoImpl implements TableRowDao {
	
	static SqlSessionFactory sqlSessionFactory = null;

	static {
		SqlSessionFactoryBuilder sessionFactoryBuilder = new SqlSessionFactoryBuilder();
		InputStream inputStream = null;
		try {
			inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
		} catch (Exception e) {
			e.printStackTrace();
		}

		sqlSessionFactory = sessionFactoryBuilder.build(inputStream);
	}



	@Override
	public void addTableRow(TableRow tableRow) {
		SqlSession session = sqlSessionFactory.openSession();
		session.insert("addTableRow", tableRow);
		
		session.commit();
		session.close();
	}



	@Override
	public List<TableRow> findRowsByTableId(int tableId) {
		SqlSession session = sqlSessionFactory.openSession();
		List<TableRow> tableRowList = session.selectList("findRowsByTableId", tableId);
		
		session.close();
		return tableRowList;
	}



	@Override
	public List<TableRow> findTableRowByUserId(Integer userId,Integer projectId) {
		SqlSession session = sqlSessionFactory.openSession();
		TableRow tableRow = new TableRow();
		tableRow.setProjectId(projectId);
		tableRow.setUserId(userId);
		
		List<TableRow> tableRowList = session.selectList("findTableRowByUserId", tableRow);
		
		session.close();
		return tableRowList;
	}



	@Override
	public List<Integer> findTableIdByUserId(int userId) {
		SqlSession session = sqlSessionFactory.openSession();
		List<Integer> list = session.selectList("findTableIdByUserId", userId);
		
		session.close();
		return list;
	}
	/*
	public static void main(String[] args) {
		List<Integer> list = new TableRowDaoImpl().findTableIdByUserId(2);
		for (Integer integer : list) {
			System.out.println(integer);
		}
	}*/



	@Override
	public void deleteTableRowByTableId(Integer tableId) {
		SqlSession session = sqlSessionFactory.openSession();
		session.delete("deleteTableRowByTableId", tableId);
		
		session.commit();
		session.close();
		
	}



	@Override
	public List<Integer> findTableIdByUIdAndPId(TableRow tablerow) {
		SqlSession session = sqlSessionFactory.openSession();
		List<Integer> list = session.selectList("findTableIdByUIdAndPId", tablerow);
		
		session.close();
		return list;
	}

}
